package com.spgf.controller.fragments;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.archtecture.model.exceptions.NegocioException;
import com.spgf.controller.R;
import com.spgf.controller.utils.PadraoFragmentAb;
import com.spgf.model.dao.CategoriaDAO;
import com.spgf.model.entities.Categoria;
import com.spgf.model.rn.CategoriaRN;

public class CategoriaMnt extends PadraoFragmentAb {

	private ListView	listview;

	@Override
	protected ViewGroup configurarViewRoot(LayoutInflater inflater) {
		return (ViewGroup) inflater.inflate(R.layout.fragment_categoria_busca, null);
	}

	@SuppressLint("SimpleDateFormat")
	private void atualizarLista(final ViewGroup root) throws NegocioException {

		final List<Categoria> ls = new CategoriaRN(root.getContext()).executarFindAll(new Categoria());

		final ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (final Categoria l : ls) {

			final DecimalFormat df = new DecimalFormat();
			df.setMaximumFractionDigits(0);
			df.setMinimumIntegerDigits(3);

			final String referencia = df.format(l.getCodigo());

			final HashMap<String, String> item = new HashMap<String, String>();
			item.put("Item", l.getNome());
			item.put("SubItem", "Ref.: " + referencia + "                           " + l.getTipo().getNome());

			list.add(item);
		}

		final String[] from = new String[] {"Item", "SubItem"};
		final int[] to = new int[] {android.R.id.text1, android.R.id.text2};
		listview.setAdapter(new SimpleAdapter(root.getContext(), list, android.R.layout.two_line_list_item, from, to));
	}

	@Override
	public void configurarTela(ViewGroup root) throws NegocioException {

		listview = (ListView) root.findViewById(R.id.categ_busca_lista_resultado);
		listview.setOnItemLongClickListener(acaolongClick);
		atualizarLista(root);
	}

	@Override
	@SuppressWarnings("unchecked")
	protected boolean executarLongClick(AdapterView<?> pParent, View pView, int pPosition, long pID) throws NegocioException {

		if (pParent.getId() == R.id.categ_busca_lista_resultado) {

			final Map<String, String> mapa = (Map<String, String>) listview.getItemAtPosition(pPosition);
			final String valor = mapa.get("SubItem").toString();
			final Integer codigo = Integer.valueOf(valor.substring(valor.indexOf("Ref.: ") + 6, valor.indexOf("Ref.: ") + 9));

			final CategoriaDAO dao = new CategoriaDAO(pView.getContext());
			dao.executeDelete(new Categoria(codigo));

			atualizarLista(pParent);
			return true;

		}

		return false;
	}

}
